# from pydantic import BaseModel
from fastapi import FastAPI, Depends
import asyncio
import pymssql
import configparser

app = FastAPI()

# class Customer(BaseModel):
#     id: int
#     name: str

@app.get("/customers")
async def get_all_customers():
    config = configparser.ConfigParser()
    config.read('config.ini')
    DATABASE_URL = f"mssql+pymssql://{config['database']['username']}:{config['database']['password']}@{config['database']['host']}:{config['database']['port']}/{config['database']['database']}"
    conn = pymssql.connect(host=DATABASE_URL.split("//")[1].split("/")[0],
                           user=DATABASE_URL.split("//")[1].split("@")[0].split("/")[0],
                           password=DATABASE_URL.split("//")[1].split("@")[0].split("/")[1],
                           database=DATABASE_URL.split("//")[1].split("@")[1].split("/")[1],
                           port=int(DATABASE_URL.split("//")[1].split("@")[1].split("/")[0]))
    cursor = conn.cursor()
    await cursor.execute("SELECT * FROM Customers")
    customers = [row[0] for row in await cursor.fetchall()]
    cursor.close()
    conn.close()
    return customers

@app.get("/customers/{page}")
async def get_customers_by_page(page: int = Query(..., ge=1)):
    config = configparser.ConfigParser()
    config.read('config.ini')
    DATABASE_URL = f"mssql+pymssql://{config['database']['username']}:{config['database']['password']}@{config['database']['host']}:{config['database']['port']}/{config['database']['database']}"
    conn = pymssql.connect(host=DATABASE_URL.split("//")[1].split("/")[0],
                           user=DATABASE_URL.split("//")[1].split("@")[0].split("/")[0],
                           password=DATABASE_URL.split("//")[1].split("@")[0].split("/")[1],
                           database=DATABASE_URL.split("//")[1].split("@")[1].split("/")[1],
                           port=int(DATABASE_URL.split("//")[1].split("@")[1].split("/")[0]))
    cursor = conn.cursor()
    offset = (page - 1) * 10
    await cursor.execute(f"SELECT * FROM Customers OFFSET {offset} ROWS FETCH NEXT 10 ROWS ONLY")
    customers = [row[0] for row in await cursor.fetchall()]
    cursor.close()
    conn.close()
    return customers

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app="app:app", port=8000, host="127.0.0.1", reload=True)